package com.lujianfei.powersearch.ui.sort

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import com.lujianfei.powersearch.R
import com.lujianfei.powersearch.adapter.SortAdapter
import com.lujianfei.powersearch.base.BaseActivity
import com.lujianfei.powersearch.database.SearchItemModel
import com.lujianfei.powersearch.databinding.ActivitySortItemBinding
import com.lujianfei.powersearch.ui.sort.touchhelper.SortDragTouchCallback
import com.lujianfei.powersearch.ui.sort.viewmodel.SortItemViewModel

class SortItemActivity : BaseActivity<ActivitySortItemBinding>() {

    companion object {

        fun jumpSortItemActivity(context: Context, item: SearchItemModel?) {
            val intent = Intent(context, SortItemActivity::class.java)
            intent.putExtra("data", item)
            context.startActivity(intent)
        }
    }

    private val sortItemViewModel: SortItemViewModel by lazy { buildViewModel() }
    private val commonAdapter by lazy { SortAdapter() }
    override fun resourceId() = R.layout.activity_sort_item

    override fun initView() {
        binding?.vm = sortItemViewModel
        val sortDragTouchCallback = SortDragTouchCallback(commonAdapter)
        val itemTouchHelper = ItemTouchHelper(sortDragTouchCallback)
        itemTouchHelper.attachToRecyclerView(binding?.listview)
        binding?.listview?.apply {
            layoutManager = LinearLayoutManager(this.context)
            addItemDecoration(DividerItemDecoration(this.context, DividerItemDecoration.VERTICAL))
            adapter = commonAdapter
        }
    }

    override fun initData() {
        parseIntent()
    }

    override fun initEvent() {
    }

    private fun parseIntent() {
        sortItemViewModel.searchItemModel = intent.getParcelableExtra("data")
        setTitleMiddleText(sortItemViewModel.searchItemModel?.name)
    }

    override val titleBarResId = R.id.toolbar
    override val menuResId: Int = R.menu.sort_item_menu

    override fun handleRightButton(itemId: Int) {
        super.handleRightButton(itemId)
        when (itemId) {
            R.id.action_sort_save ->  {
                sortItemViewModel.saveSort(commonAdapter.getData())
                finish()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        sortItemViewModel.loadData {
            commonAdapter.setData(sortItemViewModel.data)
        }
    }
}